package com.jiao.databinding3.observablefield;

import android.os.Bundle;
import android.util.Log;

import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;
import androidx.databinding.Observable;
import androidx.databinding.ObservableField;

import com.jiao.databinding3.BR;
import com.jiao.databinding3.R;
import com.jiao.databinding3.baseobservable.Goods;
import com.jiao.databinding3.databinding.ActivityMain1Binding;
import com.jiao.databinding3.databinding.ActivityMain2Binding;

import java.util.Random;
/*如需访问字段值，请使用 set() 和 get() 访问器方法
*    user.firstName.set("Google");
    int age = user.age.get();


* */
public class MainActivity2 extends AppCompatActivity {
    private ObservableGoods goods;
    private ActivityMain2Binding activityMain3Binding;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        activityMain3Binding = DataBindingUtil.setContentView(this, R.layout.activity_main2);
        goods = new ObservableGoods("code", 22, "fff");
        activityMain3Binding.setGoods(goods);
        activityMain3Binding.setGoodsHandler(new GoodsHandler());

        /*
         * 实现了 Observable 接口的类允许注册一个监听器，
         * 当可观察对象的属性更改时就会通知这个监听器，此时就需要用到 OnPropertyChangedCallback
         * */
        goods.name.addOnPropertyChangedCallback(new Observable.OnPropertyChangedCallback() {
            @Override
            public void onPropertyChanged(Observable sender, int propertyId) {
                if (propertyId == BR.name) {
                    Log.e("TAG", "BR.name"+goods.name);
                }
                Log.e("TAG", "onPropertyChanged"+propertyId);
            }
        });
        goods.details.addOnPropertyChangedCallback(new Observable.OnPropertyChangedCallback() {
            @Override
            public void onPropertyChanged(Observable sender, int propertyId) {
                if (propertyId == BR.details) {
                    Log.e("TAG", "BR.details"+goods.details);
                }
                Log.e("TAG", "onPropertyChanged"+propertyId);
            }
        });
    }

    public class GoodsHandler {

        public void changeGoodsName() {
            goods.name.set("code2");
//            goods.price.set(new Random().nextInt(100));

            //这种形式改变不了？？？？
//            goods.setDetails(new ObservableField<>("iii"));

        }
    }
}
